﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZX.BLL.Extend;
using ZX.SYS.Library;
using ZX.EHR.Library;
using ZX.Common;
using ZX.Common.Extend;
using ZX.DBModule;

namespace ZX.BLL
{
    public class BEmployeeSalary : BaseBussnies
    {
        public override bool Insert(object entitys, out string msg)
        {
            bool rs = base.Insert(entitys, out msg);
            if (rs)
            {
                RunSalaryJob();
            }
            return rs;
        }

        public override bool Update(object entitys, out string msg)
        {
            bool rs = base.Update(entitys, out msg);
            if (rs)
            {
                RunSalaryJob();
            }
            return rs;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public bool RunEffectSalary()
        {
            System.Data.DataTable _result = this.GetDataBySqlComm("select * from V_salNoEffectSalary");
            if (_result != null || _result.Rows.Count > 0)
            {
                foreach (System.Data.DataRow row in _result.Rows)
                {
                    try
                    {
                    bool f = EncryptData.EncryptSalary.SaveBaseData(row["EmployeeID"].ToString(), row["BaseSalary"].ToString(), row["BaseSalary"].ToString(), row["ValidDate"].ToString(), "1900-01-01", row["AddUser"].ToString(), "1");
                    }
                    catch(Exception e){
                    }
                        //更新
                }
                return true;
            }
            return false;
        }

        private void RunSalaryJob()
        {
            string condition = string.Empty;
            BaseEntity instance = null;
            ZX.BLL.Extend.BaseBussnies bll = null;
            IList<BaseEntity> list = null;
            try
            {
                //薪资异动后要薪资表中的薪资状态信息
                instance = ZX.Common.Globals.getEntity("hrEmployeeSalary") as BaseEntity;
                bll = new ZX.BLL.Extend.BaseBussnies(instance);
                condition = string.Format("ValidDate<='{0}'and AvilableStatus=3", DateTime.Now.ToString("yyyy-MM-dd"));//生效日期到达并且是即将使用的状态
                list = bll.GetEntitysByCondition(condition);//获取所有符合条件的记录
                if (list != null)
                {
                    foreach (BaseEntity entity in list)
                    {
                        hrEmployeeSalary hremployeeSalary = entity as hrEmployeeSalary;
                        condition = string.Format("EmployeeID='{0}' and AvilableStatus=2", hremployeeSalary.EmployeeID.ToString());
                        IList<BaseEntity> list2 = bll.GetEntitysByCondition(condition);//获取目前正在使用的薪资记录
                        if (list2 != null)
                        {
                            for (int i = 0; i < list2.Count; i++)
                            {
                                hrEmployeeSalary tempHremployeeSalary = list2[i] as hrEmployeeSalary;
                                tempHremployeeSalary.AvilableStatus = 1;//将之前正在使用的薪资状态更新为过期
                                bll = new ZX.BLL.Extend.BaseBussnies(tempHremployeeSalary);
                                bll.Update();
                            }
                        }
                        hremployeeSalary.AvilableStatus = 2;
                        bll = new ZX.BLL.Extend.BaseBussnies(hremployeeSalary);//更新薪资信息
                        bll.Update();
                    }
                }
            }
            catch
            { }
        }


        /// <summary>
        /// 计算佣金
        /// </summary>
        /// <param name="ym">年月</param>
        public void CalProvisionSalaryData(string ym)
        {
            //产品，角色，年，所属年月，条件
            System.Data.DataTable _dt = this.GetDataBySqlComm("select * from V_salProvisionData order by EffectYear");
            StringBuilder _Script=new StringBuilder("");
            _Script.AppendLine(@"Create proc sp_calEmployeeCommission 
                               (@YM     varchar(7)) as Begin");
            _Script.AppendLine("select *,0 as CommissionCoff/*佣金系数(%)*/,0 as Commission/*佣金提成*/,'N' as IsConst/*是否常数*/  into #salCommission/*临时数据表*/ from V_CrmCommisionAll where YM=@YM");  //sal佣金表数据来自于CRM相同的数据结构 增加佣金系数(CommissionCoff)，佣金提成(Commission)
            //获取某人的佣金比率
            foreach (System.Data.DataRow row in _dt.Rows)
            {
                string strSQL = "Update a set a.Commission='{0}' from  #salCommission a where ProductID='{1}' and  CommissionPostID='{2}' and SystemName='{3}' and YM=@YM ";
                //{
                _Script.AppendLine(string.Format(strSQL, row["Proportion"].ToString(), row["ProductName"].ToString(), row["RoleName"].ToString(), row["EffectYear"].ToString()));
                //}
               // else
                if (row["Condition"].ToString() != "")
                {
                    _Script.AppendLine(" and ("+row["Condition"].ToString()+")");
                }
            }
            _Script.AppendLine("end");
            this.RunSqlCommand(_Script.ToString());
            //System.Data.DataTable dt = this.GetDataBySqlComm("select * from V_CrmCommisionExtend where ProductName={0} and  rolename={1} and Y={3} and ym={4}");
            //System.Data.DataTable dt = this.GetDataBySqlComm("select * from V_CrmCommisionExtend where ProductName={0} and  rolename={1} and Y={3} and ym={4}");
            //System.Data.DataTable dt = this.GetDataBySqlComm("select * from V_CrmCommisionExtend where ProductName={0} and  rolename={1} and Y={3} and ym={4}");
        }

        /// <summary>
        /// 计算佣金
        /// </summary>
        /// <param name="ym">年月</param>
        public void CalProvisionSalaryData(DateTime startDate,DateTime EndDate,string YM)
        {
            //产品，角色，年，所属年月，条件
            System.Data.DataTable _dt = this.GetDataBySqlComm("select * from V_salProvisionData order by EffectYear");
            StringBuilder _Script = new StringBuilder("");
            _Script.AppendLine(@"Create proc sp_calTimeSpanEmployeeCommission 
                               (@YM     varchar(7),@StartDate     DateTime,@EndDate as DateTime) as Begin");
            _Script.AppendLine("select *,0 as CommissionCoff/*佣金系数(%)*/,0 as Commission/*佣金提成*/,'N' as IsConst/*是否常数*/  into #salCommission/*临时数据表*/ from V_CrmCommisionAll where YM=@YM");  //sal佣金表数据来自于CRM相同的数据结构 增加佣金系数(CommissionCoff)，佣金提成(Commission)
            //获取某人的佣金比率
            foreach (System.Data.DataRow row in _dt.Rows)
            {
                string strSQL = "Update a set a.Commission='{0}' from  #salCommission a where ProductID='{1}' and  CommissionPostID='{2}' and SystemName='{3}' and YM=@YM ";
                //{
                _Script.AppendLine(string.Format(strSQL, row["Proportion"].ToString(), row["ProductName"].ToString(), row["RoleName"].ToString(), row["EffectYear"].ToString()));
                //}
                // else
                if (row["Condition"].ToString() != "")
                {
                    _Script.AppendLine(" and (" + row["Condition"].ToString() + ")");
                }
            }
            _Script.AppendLine("end");
            this.RunSqlCommand(_Script.ToString());
            //System.Data.DataTable dt = this.GetDataBySqlComm("select * from V_CrmCommisionExtend where ProductName={0} and  rolename={1} and Y={3} and ym={4}");
            //System.Data.DataTable dt = this.GetDataBySqlComm("select * from V_CrmCommisionExtend where ProductName={0} and  rolename={1} and Y={3} and ym={4}");
            //System.Data.DataTable dt = this.GetDataBySqlComm("select * from V_CrmCommisionExtend where ProductName={0} and  rolename={1} and Y={3} and ym={4}");
        }
    }
}
